package cc.geguol.returnautoid;

import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import cc.geguol.JdbcUtil;

/**
 * 作者  Administrator
 * 时间  2017/3/30 15:38
 * 文件  JDBCDemo
 * 描述  获取自增长id
 */
public class GetAutoId {



	@Test
	public void test() throws SQLException {
		String sql = "insert into student(name) values(?)";
		Connection connection = null;
		try {
			connection = JdbcUtil.getconn();
			connection.setAutoCommit(false);
			PreparedStatement statment = connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
			statment.setString(1,"格锅");
			statment.executeUpdate();

			ResultSet resultSet = statment.getGeneratedKeys();
			if (resultSet.next()){
				int key = resultSet.getInt(1);
				System.out.println("auto_key"+key);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
			connection.rollback();
		}finally {
			connection.commit();
		}
	}
}
